<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class product extends CI_Controller {

	function product()
	{
		parent::__construct();
		$this->load->library('session');
		$this->load->library('form_validation');
    $this->load->library('encrypt');
		$this->load->library('enc');
		$this->load->model('mmaster');
                $this->load->model('mservices');
                $this->load->model('mproduct');
		$this->load->model('mglobal');
		$this->is_logged_in();
		#$this->mjadwal->saveLog();
	}
  
  public function index()
  {
  	$this->search();
  }
    function view_products(){
        $data['template'] = "shell/smooth";
        $data['main_view']      = 'f-products';
		
		$this->load->view($data['template'],$data);
    }    
        
    function view_prices(){
        $data['template'] = "shell/smooth";
        $data['main_view']      = 'f-products';
		
		$this->load->view($data['template'],$data);
    }    
    
    function getPricesData(){
        echo json_encode( $this->mproduct->getPricesData());
    }
    
     function getProductsData(){
        echo json_encode( $this->mproduct->getProductsData());
    }
    
	function is_logged_in()
	{
		$is_logged_in = $this->session->userdata('is_logged_in');
		if(!isset($is_logged_in) || $is_logged_in != true)
		{
			redirect(base_url() .'index.php/login');
		}		
	}
	
        function manage_price()
	{
                $data['template'] = "shell/smooth";
                $data['main_view']      = 'f-manage-price';
		$data['territory_name'] = $this->mproduct->getTerritoryName();  //array(); // 
		$data['SalesAffected'] =  $this->mproduct->getSalesAffected();
		$data['ConditionType'] =  $this->mproduct->getConditionType();
		$this->load->view($data['template'],$data);
        }
	
	function getProduct(){
		$id = $this->input->post("item_id");
		$data = $this->mproduct->getProductById2($id);
		if(count($data)>0){
			foreach($data as $r){
			 //$prc=$this->mproduct->getPrice($id);
				echo json_encode(array(
					'status'=>'OK',
					'kode'=>$r->item_code,
					'group'=>$r->item_group_name,
					'nama'=>$r->item_name,
					'harga'=>$r->default_price,
					'harga2'=>"Rp. ". number_format($r->default_price, 2, ',', '.')
				));
				return;
			}
		}
	}
	
	function saveProduct(){
		$item_code = $this->input->post("item_code");
		$pricing_date = $this->input->post("pricing_date");
		$retail_price = $this->input->post("retail_price");
		$condition_type = $this->input->post("condition_type");
		$condition_value = $this->input->post("condition_value");
		$sales_affected = $this->input->post("sales_affected");
		$item_group = $this->input->post("item_group");
		$item_name = $this->input->post("item_name");
		$selling_type= $this->input->post("selling_type");
		
		//$default_price = $this->mglobal->showdata("default_price","t_mtr_item",array('item_code'=>$id,'shipment_date'=>date("Y-m-d")),"dblokal");
		
		if($item_code == ""){
			echo json_encode(array(
				'status'=>'ERROR',
				'pesan'=>'Item Code is Required.'
			));
			return;
		}elseif($sales_affected == 9 && $selling_type==0){
			echo json_encode(array(
				'status'=>'ERROR',
				'pesan'=>'Selling Type is Required.'
			));
			return;
		}elseif($condition_value == ""){
			echo json_encode(array(
				'status'=>'ERROR',
				'pesan'=>'Condition Value is Required.'
			));
			return;
		}elseif($condition_type==1 && $condition_value > 0 && $condition_value >= $retail_price){
			echo json_encode(array(
				'status'=>'ERROR',
				'pesan'=>'Conditional Value tidak boleh lebih besar dari Retail Price.'
			));
			return;
		}elseif($condition_type==2 && $condition_value > 100){
			echo json_encode(array(
				'status'=>'ERROR',
				'pesan'=>'Conditional Value tidak boleh lebih besar dari/sama dengan 100%.'
			));
			return;
		}else{
			#simpan data
			
			$this->mproduct->savePricing();
			$pesan='<div id="box-messages">
					<div class="messages">
						<div id="message-success" class="message message-success">
							<div class="image">
								<img src="'. base_url() .'file/shell/smooth/resources/images/icons/success.png" alt="Success" height="32" />
							</div>
							<div class="text">
								<h6>Data berhasil dimasukkan</h6>
							</div>
							<div class="dismiss">
								<a href="#message-success"></a>
							</div>
						</div>
					</div>
				</div>';
			echo json_encode(array(
				'status'=>'OK',
				'pesan'=>$pesan
			));
			return;
		}
		
		
	}
	
	function savePricing(){
		$product = $this->mproduct->getList();
		foreach($product as $r){
			$this->mproduct->savePricing($r->item_code,$r->reseller_price);
		}
	}
	
	function countResellerPrice(){
		#hitung harga baru
		$retail_price   = $this->input->post('retail_price');
		$condition_type = $this->input->post('condition_type');
		$condition_value= $this->input->post('condition_value');
		
		$reseller_price = 0;
		if($condition_type == "1"){ #new price
			if($retail_price <= $condition_value){
				echo json_encode(array(
					'status'=>'ERROR',
					'pesan'=>'Conditional Value tidak boleh lebih besar dari Retail Price.'
				));
				return;
			}else{
				$reseller_price = $condition_value;
				echo json_encode(array(
					'status'=>'OK',
					'pesan'=>"Rp. ". number_format($reseller_price, 2, ',', '.')
				));
				return;
			}
		}elseif($condition_type == "2"){ #diskon
			if($condition_value > 100){
				echo json_encode(array(
					'status'=>'ERROR',
					'pesan'=>'Conditional Value tidak boleh lebih besar dari/sama dengan 100%.'
				));
				return;
			}else{
				$reseller_price = $retail_price - ($retail_price * $condition_value /100) ;
				echo json_encode(array(
					'status'=>'OK',
					'pesan'=>"Rp. ". number_format($reseller_price, 2, ',', '.')
				));
				return;
			}
		}
	}
	
	#######################################################
	public function read() {
		echo json_encode( $this->mproduct->get() );
	}
    
    public function search_product(){
    	redirect('./index.php/product/search');
         $data['template'] = "shell/smooth";
         
         $data['main_view']      = 'f-search-products';
        
		$data['data']['iccid']="";
        $data['data']['mdn']="";
        $data['data']['item_group_name']="";
        $data['data']['item_name']="";
        $data['data']['distributor_name']="";
        $data['data']['region']="";
        $data['data']['cluster']="";
        if($_POST)
        {
             $data['data']['param']=$this->input->post('param');
            $temp= $this->mproduct->searchProduct();
            if ($temp)
                $data['data'] =$temp[0];
            else
                $data['data']['iccid']="Barang Tidak ditemukan";
        }
		$this->load->view($data['template'],$data);
    }
	
	public function reads() {
		echo json_encode( $this->mproduct->gets() );
	}


	## Pencarian Produk ###################################################################
	## yaddis@nutech-integrasi.com
	## 09/10/2012
	#######################################################################################
  public function search()
  {
    $template = "shell/smooth";
    $data["main_view"] = "f-search";

    // $data["result"] = $this->mproduct->search_product('89622811410000107305'); 
    // print_r($data);
    if($_POST)
      { 
        $this->form_validation->set_rules('key', 'Form', 'required');
        if ($this->form_validation->run() != FALSE)
        {
          $data["result"] = $this->mproduct->search_product(trim($this->input->post('key'))); 
          $data['search'] = 1;
        }
        else
        {
          $data["result"] = false; 
          $data['search'] = 0;
        }
      }
    else 
      {
        $data["result"] = false; 
        $data['search'] = 0;
      }
      
    $this->load->view($template, $data, FALSE);
  }

  public function bulk_search($value='')
  {
  	# code...
  }
}
?>